<?php
namespace app\admin\controller;

use think\Controller;
use app\admin\model\Login as loginModel;
use think\Session;
use think\Db;
use think\captcha\Captcha;

class Login extends Controller
{

	public function index()
	{
		if ( Session::get('aid')) {
			$this->success('正在前往后台','index/index');die;
		}
		return $this->fetch();
	}
	public function doLogin()
	{	
 		// 判断验证码
		$code = $_POST['code'];
		$captcha = new Captcha();
		if( !$captcha->check($code))
		{
			$this->error('验证码错误','login/index');die;
		}
		// 验证数据库
        $data = $_POST;
        $userName = $data['userName'];
        $pwd = $data['password'];
        // 验证表单数据
        $res = Db::name('admin')
        	->field('aid,userName')
            ->where(' userName = "'.$userName.'" and password = "'.md5($pwd).'" ')
            ->find();
        // 判断是否登录成功
    	if ( !$res ) {
    		$this->error('登录失败','login/index');die;
    	}
    	// 储存session数据
    	Session::set('userName',$res['userName']);
    	Session::set('aid',$res['aid']);

    	//根据管理员aid获取对应的节点信息
    	$nodelist = Db::table(['xt_admin_relate_role'=>'ar','xt_admin_access'=>'aa','xt_admin_node'=>'an'])
				->where('ar.roleId = aa.roleId AND aa.nodeId = an.id')
				->where('ar.adminId',$res['aid'])
				->order('an.level asc')
				->select();
		$node = array();
		$node['Index'] = array('index','info');

		$pidArr = array();
		//遍历重新拼装
		foreach( $nodelist as $key => $v ){
			if ( $v['level'] == 1  ) {
				// 判断级别 获取控制器名
				$node[$v['name']] = array();
				$pidArr[$v['id']] = $v['name'];
			} else {
				$key = $pidArr[$v['pid']];
				$node[$key][] = $v['name'];
			}
		}

    	Session::set('node',$node);
    	$this->success('登录成功','index/index');die;

	}

	// 退出登陆
	public function loginOut()
	{
		session(null);
		if ( empty(Session::get()) ) {
			$this->success('安全退出','login/index');die;
		}
	}
}